﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using DAO;
using DTO;

namespace BUS
{
    public class PhieuBanHang_BUS
    {
        private static PhieuBanHang_BUS m_instance = null;

        public static PhieuBanHang_BUS Instance
        {
            get
            {
                if (m_instance == null)
                {
                    m_instance = new PhieuBanHang_BUS();
                }
                return m_instance;
            }
        }

        /// <summary>
        /// Lấy mã khách hàng lớn nhất
        /// </summary>
        /// <returns></returns>
        public string LayMaPhieuBanHangMax()
        {
            DataTable dt = PhieuBanHang_DAO.Instance.LayMaPhieuBanHangMax();
            // Bi loi
            if (dt == null)
                return null;

            DataRowCollection list = dt.Rows;
            if (list.Count == 0)
                return "n/a";

            DataRow row = list[0];
            string maphieu = (string)row["MaPhieuBanHang"];

            return maphieu;
        }

        /// <summary>
        /// Thêm phiếu bán hàng mới
        /// </summary>
        /// <param name="phieu"></param>
        /// <returns></returns>
        public bool ThemPhieuBanHangMoi(PhieuBanHang_DTO phieu)
        {
            return PhieuBanHang_DAO.Instance.ThemPhieuBanHangMoi(phieu.NgayBan.ToString(), phieu.NgayThanhToan.ToString(), phieu.MaKhachHang, phieu.TongTien);
        }

        /// <summary>
        /// Lấy danh sách phiếu bán hàng trả chậm
        /// </summary>
        /// <param name="makh"></param>
        /// <returns></returns>
        public List<PhieuBanHang_DTO> LayDanhSachPhieuBanHangTraCham(string makh)
        {
            List<PhieuBanHang_DTO> result = new List<PhieuBanHang_DTO>();

            DataTable dt = PhieuBanHang_DAO.Instance.LayDanhSachPhieuBanHangTraCham(makh);
            if (dt == null)
                return null;

            DataRowCollection list = dt.Rows;
            if (list.Count == 0)
                return result;
            for (int i = 0; i < list.Count; i++)
            {
                DataRow row = list[i];
                string mapbh = (string)row["MaPhieuBanHang"];
                DateTime ngayban = (DateTime)row["NgayBan"];
                DateTime ngaythanhtoan = (DateTime)row["NgayThanhToan"];
                decimal tien = (decimal)row["TongTien"];
                long tongtien = (long)tien;
                //DateTime ngban = DateTime.Parse(ngayban);
                result.Add(new PhieuBanHang_DTO(mapbh, ngayban, ngaythanhtoan, makh, tongtien));
            }
            return result;
        }
    }
}
